<template>
  <div class="param_record">
    <div class="mes_tab_close">
      <el-tabs v-model="tabsIndex" type="card" :closable="!readOnly && recordsList.length > 1" @tab-remove="removeTab">
        <el-tab-pane
          v-for="(item, index) in recordsList"
          :key="index"
          :label="'记录表' + (index + 1)"
          :name="(index + 1).toString()">
          <div class="template_name">参数记录表：{{item.name}}</div>
        </el-tab-pane>
      </el-tabs>
      <div class="table_container"
           style="width: 100%">
        <el-table
          ref="tableNode"
          border
          style="width: 100%"
          :data="recordsList[parseInt(tabsIndex) - 1].inventory"
          :cell-class-name="classJudge"
          max-height="450">
          <el-table-column
            prop="name"
            label="参数项目"
            min-width="180"
            class-name="bg_gray"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="typeLabel"
            label="数据类型"
            min-width="70"
            class-name="bg_gray"
            show-overflow-tooltip
            align="center">
          </el-table-column>
          <el-table-column
            prop="lowerLimit"
            label="参考下限"
            min-width="70"
            class-name="bg_gray"
            :formatter="setDefault"
            show-overflow-tooltip
            align="center">
          </el-table-column>
          <el-table-column
            prop="upperLimit"
            label="参考上限"
            min-width="70"
            class-name="bg_gray"
            :formatter="setDefault"
            show-overflow-tooltip
            align="center">
          </el-table-column>
          <el-table-column
            :resizable="false"
            prop="value"
            label="值"
            class-name="edit_cell"
            min-width="300">
            <template slot-scope="scope">
              <template v-if="readOnly">
                <div class="fixed_box" v-if="scope.row.typeValue === 'Attachment'">
                  <span class="device_file_name read_only">{{scope.row.value}}</span>
                  <div class="mes_btn">
                    <el-button size="mini" :disabled="!scope.row.value" @click="openDeviceFile(scope.row.value)" class="get_file_name" type="primary" plain>
                      <span>设备附件详情</span>
                    </el-button>
                  </div>
                </div>
                <div class="read_only_txt" v-else>{{scope.row.value}}</div>
              </template>
              <div v-else class="fixed_box">
                <template v-if="scope.row.typeValue === 'Number'">
                  <el-input clearable
                            placeholder="请输入内容"
                            v-model.trim="scope.row.value" size="mini"></el-input>
                </template>
                <template v-else-if="scope.row.typeValue === 'Date'">
                  <el-date-picker
                    v-model="scope.row.value"
                    value-format="yyyy-MM-dd"
                    size="mini"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </template>
                <template v-else-if="scope.row.typeValue === 'Text'">
                  <el-input
                    type="textarea"
                    resize="none"
                    v-model="scope.row.value"
                    :autosize="{ minRows: 1, maxRows: 2}"
                    :maxlength="50"
                    placeholder="请输入">
                  </el-input>
                </template>
                <template v-else-if="scope.row.typeValue === 'Remarks'">
                  <el-input
                    type="textarea"
                    resize="none"
                    v-model="scope.row.value"
                    :autosize="{ minRows: 1, maxRows: 4}"
                    :maxlength="1000"
                    placeholder="请输入">
                  </el-input>
                </template>
                <template v-else-if="scope.row.typeValue === 'Logic'">
                  <el-select
                    size="mini"
                    v-model="scope.row.value">
                    <el-option label="请选择" value=""></el-option>
                    <el-option label="是" value="True"></el-option>
                    <el-option label="否" value="False"></el-option>
                  </el-select>
                  <!--<el-radio v-model="scope.row.value" label="True">是</el-radio>-->
                  <!--<el-radio v-model="scope.row.value" label="False">否</el-radio>-->
                </template>
                <template v-else-if="scope.row.typeValue === 'Selection'">
                  <el-select
                    size="mini"
                    v-model="scope.row.value">
                    <el-option label="请选择" value=""></el-option>
                    <el-option
                      v-for="item1 in scope.row.selections"
                      :key="item1"
                      :label="item1"
                      :value="item1">
                    </el-option>
                  </el-select>
                </template>
                <template v-else-if="scope.row.typeValue === 'Attachment'">
                  <span class="device_file_name" v-if="scope.row.value">{{scope.row.value}}</span>
                  <span class="device_file_name is_placeholder" v-else>请点击生成设备文件名</span>
                  <div class="mes_btn">
                    <el-button size="mini" class="get_file_name" @click="getDeviceFileName(scope)" type="primary" plain>
                      <i class="iconfont icon-btn_addnew"></i>
                      <span>生成</span>
                    </el-button>
                  </div>
                </template>
                <template v-else-if="scope.row.typeValue === 'Device'">
                  <el-select
                    v-model="scope.row.value"
                    size="mini"
                    value-key="id"
                    multiple
                    collapse-tags
                    placeholder="请选择">
                    <el-option
                      v-for="item1 in deviceList"
                      :key="item1.id"
                      :label="item1.name"
                      :value="item1">
                    </el-option>
                  </el-select>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="unitLabel"
            label="计量单位"
            min-width="70"
            :resizable="false"
            class-name="bg_gray"
            :formatter="setDefault"
            show-overflow-tooltip
            align="center">
          </el-table-column>
        </el-table>
      </div>
      <span class="tab_new_btn"
            v-if="!readOnly"
            @click="addTab"><i class="iconfont icon-btn_addnew"></i>新增</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ParamRecord',
  computed: {
    // 模板数据类型
    TemplateValueType() {
      return this.$store.state.dict.TemplateValueType.labels || []
    },
    // 模板数据单位
    ParameterUnitType() {
      return this.$store.state.dict.ParameterUnitType.labels || []
    }
  },
  data() {
    return {
      // 是否已修改
      isEdit: null,
      // 模板
      paramTemplate: {},
      // 记录
      recordsList: [{
        name: '',
        inventory: []
      }],
      // 记录表
      tabsIndex: '1',
      // 设备列表
      deviceList: [],
      // 是否只读
      readOnly: false,
      // 工序Number
      workstageNumber: ''
    }
  },
  watch: {
    recordsList: {
      handler(now, old) {
        if (this.isEdit === false) {
          this.isEdit = true
        }
      },
      deep: true
    }
  },
  destroyed() {
    this.tabsIndex = '1'
    this.isEdit = null
  },
  methods: {
    classJudge({row, column}) {
      if (row.typeValue !== 'Number' || column.property !== 'value') return ''
      let lowerLimit = Number(row.lowerLimit)
      let upperLimit = Number(row.upperLimit)
      let val = Number(row.value)
      if (isNaN(row.value)) {
        return ''
      } else if (!isNaN(row.lowerLimit) && val < lowerLimit) {
        return 'warn_number'
      } else if (!isNaN(row.upperLimit) && val > upperLimit) {
        return 'warn_number'
      } else {
        return ''
      }
    },
    // 设置默认显示值
    setDefault(row, column, cellValue, index) {
      if (cellValue === null || cellValue === undefined) return '-'
      return cellValue
    },
    // 显示设备附件详情
    openDeviceFile(val) {
      this.$emit('openDeviceFile', val)
    },
    // 初始化
    initParam(recordData, workstageNumber) {
      this.workstageNumber = workstageNumber
      // 如果模板存在
      if (recordData.paramTemplate) {
        this.paramTemplate = {
          name: recordData.paramTemplate.name,
          inventory: this.addLabel(recordData.paramTemplate.inventory)
        }
      }
      // 如果设备列表存在
      if (recordData.deviceList) this.deviceList = recordData.deviceList
      // 如果是只读
      if (recordData.readOnly) this.readOnly = recordData.readOnly
      if (recordData.records) {
        // 如果记录存在
        let list = JSON.parse(recordData.records)
        this.recordsList = list.map(item => {
          item.inventory = this.addLabel(item.inventory)
          return item
        })
      } else if (!this.readOnly) {
        // 如果记录不存在且非只读
        this.recordsList = [JSON.parse(JSON.stringify(this.paramTemplate))]
        this.deviceList = this.deviceList.filter(item => item.useFlag === '1')
      } else {
        // 如果记录不存在且只读
        this.recordsList = [{
          name: '',
          inventory: []
        }]
      }
      this.$nextTick(() => {
        this.isEdit = false
        this.$refs.tableNode.doLayout()
      })
    },
    // 生成设备文件号
    getDeviceFileName(scope) {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/generatefilename',
        data: {
          workstageNumber: this.workstageNumber
        },
        noCommit: true
      }).then(res => {
        this.$set(scope.row, 'value', res.message)
      })
    },
    // 初始化模板
    addLabel(inventory) {
      let list = typeof inventory === 'string' ? JSON.parse(inventory) : inventory
      return list.map(item => {
        let obj = Object.assign({}, item)
        // 如果有单位
        if (obj.unit) {
          let unit = this.ParameterUnitType.find(item => item.id === obj.unit) || {}
          obj.unitLabel = unit.label
          obj.unitValue = unit.value
        }
        // 如果有类型
        if (obj.type) {
          let type = this.TemplateValueType.find(item => item.id === obj.type) || {}
          obj.typeLabel = type.label
          obj.typeValue = type.value
          if (type.value === 'Selection' && !this.readOnly) {
            obj.value = obj.value || ''
            // 类型为选项
            obj.selections = obj.selections.replace(/，/ig, ',').split(',')
          }
          if (type.value === 'Logic' && this.readOnly) {
            obj.value = obj.value || ''
            // 类型为逻辑
            if (obj.value === 'True') {
              obj.value = '是'
            } else if (obj.value === 'False') {
              obj.value = '否'
            }
          } else if (type.value === 'Logic') {
            obj.value = obj.value || ''
          }
          if (type.value === 'Device' && !this.readOnly) {
            // 类型为设备,非只读，把已选设备加入下拉列表
            obj.value = obj.value || []
            this.deviceList = this.deviceList.filter(item => obj.value.some(ids => ids.id === item.id) || item.useFlag === '1')
          } else if (type.value === 'Device' && this.readOnly) {
            // 类型为设备,只读
            if (obj.value) {
              obj.value = obj.value.map(item => item.name).join(',')
            } else {
              obj.value = ''
            }
          }
        }
        return obj
      })
    },
    // 添加记录表
    addTab() {
      this.recordsList.push(JSON.parse(JSON.stringify(this.paramTemplate)))
      this.tabsIndex = (this.recordsList.length).toString()
    },
    // 删除记录表
    removeTab(targetIndex) {
      this.$confirm('是否删除当前参数记录表？', '删除提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '关闭',
        confirmButtonClass: 'el-button--danger',
        customClass: 'mes_confirm',
        type: 'warning'
      }).then(() => {
        this.recordsList.splice(parseInt(targetIndex) - 1, 1)
        this.tabsIndex = (this.recordsList.length).toString()
      })
    },
  }
}
</script>
<style lang="less">
  .param_record {
    .table_container {
      .cell{
        padding: 0 5px;
      }
      .el-table__body {
        .bg_gray{
          background-color: @mesNoEditableBg;
        }
        .cell{
          height: auto;
        }
        .warn_number .el-input__inner{
          color: #f8000f;
          font-weight: bold;
        }
        .edit_cell {
          .fixed_box{
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .cell{
            padding: 0px;
          }
          .el-input__inner, .el-textarea__inner{
            background-color: transparent;
            border: 0;
            font-size: 14px;
            padding-left: 10px;
            text-align: left;
          }
          .el-input-number--mini{
            width: 100%;
          }
          .el-textarea__inner{
            padding-top: 0px;
            padding-bottom: 0px;
            line-height: 18px;
          }
          .el-textarea{
            vertical-align: middle;
          }
          .el-date-editor{
            width: 100%;
            padding-left: 0px;
            .el-input__prefix{
              left: 5px;
            }
            .el-input__inner{
              padding-left: 30px;
            }
          }
          .el-select{
            width: 100%;
          }
          .device_file_name{
            flex: 1;
            text-align: left;
            box-sizing: border-box;
            padding-left: 10px;
            &.is_placeholder{
              color: #bbbdc4;
            }
            .el-input__inner {
              background-color: #fff;
            }
          }
          .get_file_name{
            min-width: 60px;
            height: 22px;
            padding: 0px 5px;
            box-sizing: border-box;
            line-height: 20px;
            margin-right: 10px;
            .iconfont{
              font-size: 12px;
            }
          }
        }
      }
    }
  }
</style>
<style scoped lang="less">
  .param_record {
    width: 100%;
    .mes_tab_close{
      position: relative;
    }
    .tab_new_btn {
      position: absolute;
      top: 0px;
      right: 20px;
      height: 30px;
      line-height: 30px;
      color: #333;
      cursor: pointer;
      font-size: 12px;
      .iconfont {
        font-size: 12px;
        color: #00b4ff;
        padding-right: 5px;
      }
    }
    .read_only_txt{
      padding: 0px 10px;
    }
    .template_name {
      height: 40px;
      line-height: 40px;
      font-size: 12px;
      color: #333;
    }
  }
</style>
